import jwt
from jwt import PyJWTError
from comment.utils import const
from datetime import datetime, timedelta
from flask import current_app
from comment.models.user import User


def generate_tokens(user_id):
    """
    采用pyjwt生成token
    :param user_id: 用户ID
    :return:
    """
    payload = {  # 准备第一个参数
        'id': user_id,
        'exp': datetime.utcnow() + timedelta(seconds=const.JWT_EXPIRY_SECOND)
    }
    return jwt.encode(payload=payload, key=const.SECRET_KEY, algorithm='HS256')

def verify_tokens(token_str):
    """
    采用pyjwt验证token
    :param token_str:
    :return:
    """
    try:
        data = jwt.decode(token_str, key=const.SECRET_KEY, algorithms='HS256')
        current_app.logger.info(data)
    except PyJWTError as e:
        return {'msg': 'token 验证失败'}, 400
    user = User.query.filter(User.id == data['id']).first()
    if user and user.status != 0:
        return {'msg': '用户已经过期'}, 400
    return {'id': user.id}
